// pages/detail/detail.js
const app = getApp()
Page({

  /**
   * 页面的初始数据 
   */
  data: {
    details: {},
    windowWidth: 0,
    images: [],


    currentPageUrl: '',
    currentItemId: 0,
    num: 1,

    text_area_height: 120,
    text_area_padding_bottom: 30,
    text_area_txt: '【限时特价全国包邮】【好棉袜5双10双装】袜子男士秋冬中筒袜短袜黑白商务纯色棉袜子四季吸汗防臭运动袜短袜长袜\n原价7.8元\n券后价5.8元\n下单地址: http://url.cn/51P1eoY',

    coupon_image: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取当前窗口宽度
    var res = wx.getSystemInfoSync();
    this.setData({
      windowWidth: res.windowWidth
    });
    //ss





    //获取当前URL
    wx.showShareMenu({
      withShareTicket: false
    });
    // this.data.currentPageUrl = getCurrentPages()[1].route;
    // console.log(getCurrentPages());

    // console.log(options);
    this.data.currentItemId = options.itemid;


    //获取当前ID的详细数据
    var defaultUrl = app.globalData.commonUrl;
    var that = this;
    wx.showLoading({
      title: '拼命加载中',
      mask: true,
      success() {
        wx.request({
          url: defaultUrl,
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: 'POST',
          data: {
            m: 'detail',
            itemid: that.data.currentItemId
          },
          success: function (res) {
            console.log(res.data);
            var txt = res.data.result.content;
            var t = txt.replace(/\\n/g, ' \n');
            //对图片数组进行清洗
            var images = [];
            for (let i in res.data.result.images) {
              if (i == 0) {
                images.push({
                  selected: true,
                  id: i, 
                  image: res.data.result.images[i]
                })
              }
              else {
                images.push({
                  selected: false,
                  id: i,
                  image: res.data.result.images[i]
                })
              }
            };
            // var i=t.indexOf('原价');
            // t=t.substr(0,i);
            that.setData({
              details: res.data.result,
              txt: t,
              images: images
            });
            wx.hideLoading();
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /***********add by yanyingjie 2018-03-27 begin*************/
  // 查看大图
  onTapScale(e) {
    var that = this;
    console.log(e);
    var img = e.currentTarget.dataset.item.image;
    wx.previewImage({
      current: img, // 当前显示图片的http链接
      urls: [img] // 需要预览的图片http链接列表
    })
  },
  // 购买、复制到剪贴板
  onTapBuy() {
    var that = this;
    //筛选出选中的图片
    var selectedImg = [];
    that.data.images.forEach(item => {
      if (item.selected == true) {
        selectedImg.push(item);
      }
    })
    // 判断选中的数量是否为空
    if (selectedImg.length == 0) {
      wx.showToast({
        title: '当前没有选中图片，请重新选择！',
        icon:'none'
      })
    }
    else {
      //复制分享
      wx.setClipboardData({
        data: that.data.details.content,
        success: function (res) {
          wx.getClipboardData({
            success: function (res) {
              console.log(res.data) // data
              wx.showModal({
                title: '温馨提示',
                content: '点击确定保存文案和选中的图片到相册，可手动分享到朋友圈哦',
                confirmText: '确定',
                cancelText: '取消',
                success: function (res) {
                  if (res.confirm) {
                    console.log('用户点击确定');
                    //保存选中的图片到本地
                    selectedImg.forEach(item => {
                      setTimeout(function () {
                        wx.downloadFile({
                          url: item.image,
                          success: function (res) {
                            console.log(res)
                            wx.saveImageToPhotosAlbum({
                              filePath: res.tempFilePath,
                              success: function (res) {
                                console.log(res)
                              }
                            })
                          }
                        })
                      }, 30);
                    })
                  } else if (res.cancel) {
                    console.log('用户点击取消');
                  }
                }
              })
            }
          })
        }
      })
    }
  },
  // 分享到微信
  shareToWx() {
    // wx.showShareMenu({
    //   withShareTicket: true
    // })
  },
  // 分享到朋友圈
  shareToFriends() {
    var that = this;
    //保存选中的图片到本地
    this.data.images.forEach(item => {
      if (item.selected === true) {
        wx.downloadFile({
          url: item.image,
          success: function (res) {
            console.log(res)
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: function (res) {
                console.log(res)
              }
            })
          }
        })
      }
    })
  },
  //转发
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: this.data.details.title,
      path: 'pages/detail/detail?itemid=' + this.data.currentItemId,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  // 取消勾选
  onTapSelect(e) {
    var index = e.currentTarget.dataset.item.id;
    this.data.images[index].selected = false;
    var images = this.data.images;
    this.setData({
      images: images
    });
    this.count();
    console.log(this.data.images);
  },
  // 勾选
  onTapCancelSelect(e) {
    var index = e.currentTarget.dataset.item.id;
    this.data.images[index].selected = true;
    var images = this.data.images;
    this.setData({
      images: images
    });
    this.count();
    console.log(this.data.images);
  },
  //计算选中的数量
  count() {
    var arr = this.data.images.filter(item => {
      return item.selected == true
    });
    this.setData({
      num: arr.length
    });
  },
  // 复制文案
  copyTxt() {
    wx.setClipboardData({
      data: this.data.details.content,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            console.log(res.data) // data
            wx.showToast({
              title: '复制成功',
              icon: 'success',
              duration: 1200
            })
          }
        })
      }
    })
  },
})



 /***********add by yanyingjie 2018-03-27 end*************/